<template>
  <div>
    <div id="components-form-demo-advanced-search">
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          角色名称：<a-input :maxLength="128" style="width: 60%" v-model="searchData.roleName" />
        </a-col>
        <a-col :span="6">
          <div>
            <a-button
              type="primary"
              class="searchBtn"
              @click="
                () => {
                  getRoleTableList();
                }
              "
            >
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="resetSearch"
            >
              重置
            </a-button>
          </div>
        </a-col>
        <a-col :span="6"> </a-col>
        <a-col :span="6"> </a-col>
      </a-row>
    </div>
    <!-- //新增按钮 -->
    <div style="margin-top: 20px">
      <a-button
        type="primary"
        style="
          background: #66b1ff;
          color: #fff;
          border: none;
          margin-left: 8px;
          margin-right: 20px;
        "
        @click="showModal"
      >
        新增角色
      </a-button>
    </div>

    <!-- //表格 -->
    <a-spin tip="Loading..." :spinning="spinning">
      <a-table
        :columns="columns"
        :data-source="roleTabData"
        :pagination="false"
      >
        <span slot="action" class="action" slot-scope="text, record">
          <a slot="action" href="javascript:;" @click="editRow(record)">编辑</a>
          <a-divider type="vertical" />
          <a
            slot="action"
            style="color: red; border-color: red"
            href="javascript:;"
            @click="delRoleRow(record)"
            >删除</a
          >
        </span>
        <span slot="roleDesc" slot-scope="text, record">
          {{ record.roleDesc === null ? "暂无" : record.roleDesc }}
        </span>
        <span slot="delFlag" slot-scope="text, record">
          <span :style="record.delFlag === '0' ? 'color:#3EAE7C' : 'color:red'">
            {{ record.delFlag === "0" ? "启用" : "停用" }}
          </span>
        </span>
      </a-table>
    </a-spin>
    <!-- 分页器 -->
    <div style="margin: 20px 0; text-align: center">
      <a-config-provider>
        <a-pagination
          :current="searchData.current"
          show-size-changer
          :pageSizeOptions="['10', '20', '30']"
          :show-total="
            total => `${$t('m.page.Total')} ${total} ${$t('m.page.items')}`
          "
          @showSizeChange="showChange"
          :buildOptionText="
            props => ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
          "
          show-quick-jumper
          :default-current="searchData.current"
          :total="total"
          @change="onChangePage"
        />
      </a-config-provider>
    </div>

    <a-modal v-model="roleVisible" :title="title">
      <template slot="footer" class="modelBtn">
        <a-button
          @click="roleVisible = false"
          style="background: #d7d7d7; color: #fff; border: none"
          >取消</a-button
        >

        <a-button
          :loading="onSubmitLoading"
          type="primary"
          @click="onSubmit('add')"
          >确认</a-button
        >
      </template>
      <div>
        <div style="padding: 14px">
          <a-form-model
            ref="ruleForm"
            :model="roleForm"
            :rules="roleRules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-model-item label="角色名称" prop="roleName">
              <a-input :maxLength="128" v-model="roleForm.roleName" />
            </a-form-model-item>
            <a-form-model-item label="角色描述" prop="roleDesc">
              <a-textarea
                v-model="roleForm.roleDesc"
                :auto-size="{ minRows: 3, maxRows: 5 }"
                :maxLength="128"
              />
            </a-form-model-item>
            <a-form-model-item label="是否启用" prop="delFlag">
              <a-switch default-checked v-model="roleForm.delFlag" />
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>

      <h3 style="margin-left: 20px">权限分配</h3>
      <div style="width: 100%; border-bottom: 1px solid #ccc"></div>
      <div class="tree" style="padding: 10px">
        <a-tabs default-active-key="1">
          <a-tab-pane key="1" tab="PC端">
            <a-tree
              checkStrictly
              v-model="checkedKeysPC"
              checkable
              :expanded-keys="expandedKeysPC"
              :auto-expand-parent="false"
              :tree-data="roleTreeDataPC"
              @expand="onExpandPC"
              @check="onCheckPC"
            />
          </a-tab-pane>
          <a-tab-pane key="2" tab="移动端" force-render>
            <a-tree
              v-model="checkedKeysMobile"
              checkable
              :expanded-keys="expandedKeysMobile"
              :auto-expand-parent="false"
              :tree-data="roleTreeDataMobile"
              @expand="onExpandMobile"
              @check="onCheckMobile"
            />
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  sysRole_page,
  sysRole_tree,
  add_sysRole,
  tree_sysRoleTree,
  info_sysRole,
  del_sysRole
} from "@/apis/system/Permission/AccManagement";
export default {
  created() {
    this.getRoleTableList();
    this.getRoleTreeList();
  },
  data() {
    return {
      spinning: false,
      onSubmitLoading: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
      roleForm: {
        roleName: null,
        roleDesc: null,
        delFlag: true,
        persIds: [],
        roleId: null
      },
      roleRules: {
        roleName: [
          {
            required: true,
            message: "角色名称不能为空",
            trigger: "blur"
          }
        ]
      },
      roleVisible: false,
      // 搜索数据
      searchData: {
        current: 1,
        roleName: null,
        size: 10
      },
      expand: false,
      //   表格数据
      roleTabData: [],
      //   总条数
      total: 5,
      //PC打开的树
      expandedKeysPC: [],
      //移动打开的树
      expandedKeysMobile: [],
      //PC选中的树
      checkedKeysPC: [],
      //pc端父节点的值
      // checkedKeysParentPC: [],
      //移动选中的树
      checkedKeysMobile: [],
      //移动端父节点的值
      checkedKeysParentMobile: [],
      //PC端树
      roleTreeDataPC: [],
      //移动端树
      roleTreeDataMobile: [],
      title: ""
    };
  },
  methods: {
    //删除每一行
    async delRoleRow(record) {
      let _this = this;
      this.$confirm({
        title: "确定要删除角色为" + record.roleName + "的数据吗?",
        cancelText: "取消",
        okText: "确定",
        onOk() {
          return new Promise(resolve => {
            setTimeout(async () => {
              let { code } = await del_sysRole(record.key);
              if (code === "10000") {
                _this.getRoleTableList();
                resolve();
              } else {
                resolve();
                // _this.$message.error(message);
              }
            });
          }, 1000).catch(() => console.log("Oops errors!"));
        },
        onCancel() {}
      });
    },
    // PC树形打开
    onExpandPC(expandedKeys) {
      this.expandedKeysPC = expandedKeys;
    },
    // 移动树形打开
    onExpandMobile(expandedKeys) {
      this.expandedKeysMobile = expandedKeys;
    },
    // PC树形选中
    onCheckPC(checkedKeys) {
      // console.log(info);
      this.checkedKeysPC = checkedKeys.checked;
      // this.checkedKeysParentPC = info.halfCheckedKeys;
    },
    // 移动端形选中
    onCheckMobile(checkedKeys) {
      // console.log("onCheck", checkedKeys, info);
      this.checkedKeysMobile = checkedKeys.checked;
      // this.checkedKeysParentMobile = info.halfCheckedKeys;
    },
    //模态框确认按钮
    onSubmit() {
      this.onSubmitLoading = true;
      let sumitData = { ...this.roleForm };
      sumitData.persIds = this.checkedKeysPC;
      sumitData.delFlag = this.roleForm.delFlag ? "0" : "1";
      if (this.checkedKeysPC.length <= 0) {
        this.$message.error("请分配权限！");
        this.onSubmitLoading = false;
        return false;
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          setTimeout(async () => {
            let { code, message } = await add_sysRole(sumitData);
            if (code === "10000") {
              this.onSubmitLoading = false;
              this.getRoleTableList();
              this.roleVisible = false;
            } else {
              this.$message.error(message);
              this.onSubmitLoading = false;
            }
          }, 1000);
        } else {
          this.onSubmitLoading = false;
          return false;
        }
      });
    },
    //显示模态框
    showModal() {
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields();
      }
      this.checkedKeysPC = [];
      this.checkedKeysMobile = [];
      this.expandedKeysMobile = [];
      this.expandedKeysPC = [];
      this.roleForm.roleName = null;
      this.roleForm.roleDesc = null;
      this.roleForm.delFlag = true;
      this.roleForm.roleId = null;
      this.roleVisible = true;
      this.title = "新增角色";
    },
    //   编辑按钮
    async editRow(record) {
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields();
      }
      let res = await info_sysRole(record.roleId);
      if (res.code === "200") {
        this.roleForm.roleName = res.responseBody.roleName;
        this.roleForm.delFlag = res.responseBody.delFlag === "0" ? true : false;
        this.roleForm.roleDesc = res.responseBody.roleDesc;
        this.roleForm.roleId = res.responseBody.roleId;
      }
      let { code, responseBody } = await tree_sysRoleTree(record.roleId);
      if (code === "200") {
        this.checkedKeysPC = [];
        this.roleVisible = true;
        this.title = "修改角色";
        responseBody.forEach(item => {
          this.checkedKeysPC.push(item.permissionId);
        });
      }
    },
    //重置按钮
    resetSearch() {
      this.searchData.roleName = null;
      this.getRoleTableList();
    },
    //分页器事件
    onChangePage(pageNumber) {
      this.searchData.current = pageNumber;
      this.getRoleTableList();
    },
    //页码变更
    showChange(size, current) {
      this.searchData.current = size;
      this.searchData.size = current;
      this.getRoleTableList();
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //获取角色表格列表
    async getRoleTableList() {
      this.spinning = true;
      let { code, responseBody } = await sysRole_page(this.searchData);
      if (code === "200") {
        this.total = responseBody.total * 1;
        this.roleTabData = [...responseBody.records];
        if (this.roleTabData.length >= 1) {
          this.roleTabData.forEach(item => {
            item.key = item.roleId;
          });
        }
        this.spinning = false;
      }
    },
    //获取权限树
    async getRoleTreeList() {
      let { code, responseBody } = await sysRole_tree(1);
      if (code === "200") {
        this.roleTreeDataPC = this.resetTree(responseBody.allTree);
      }
    },
    //重构树
    resetTree(data) {
      data.forEach(item => {
        item.title = item.permissionName;
        item.key = item.id;
        if (item.children && item.children.length >= 1) {
          this.resetTree(item.children);
        }
      });
      return data;
    }
  },
  computed: {
    columns() {
      return [
        {
          title: "角色名称",
          dataIndex: "roleName",
          align: "center",
          width: "20%"
        },
        {
          title: "角色描述",
          dataIndex: "roleDesc",
          align: "center",
          scopedSlots: { customRender: "roleDesc" },
          width: "40%"
        },
        // {
        //   title: "权限",
        //   dataIndex: "roleType",
        //   align: "center",
        //   width: "20%",
        // },
        {
          title: "状态",
          dataIndex: "delFlag",
          scopedSlots: { customRender: "delFlag" },
          align: "center",
          width: "20%"
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 250,
          fixed: "right"
        }
      ];
    }
  }
};
</script>

<style lang="less" scoped>
.searchBtn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.searchBtn:hover {
  background: #3eae7c;
  color: #fff;
}
.action {
  a {
    border-bottom: 1px solid rgb(41, 41, 224);
    color: rgb(41, 41, 224);
  }
}
/deep/.ant-modal-body {
  padding: 0;
}
</style>
